import Handle from "./handle";

import { getToken, setToken } from "@/utils/token";
import { refreshToken as refreshTokenApi } from "@/api/current";

let isRefreshing = false; // 标记是否正在刷新 token
let requests = []; // 存储待重发请求的数组

const handleResend = (http, config, res) => {
  const { accessToken } = res;
  setToken(res);
  // 重发
  config.headers.Authorization = accessToken;
  requests.forEach((request) => request());
  requests = [];
  return http(config);
};

const handleRefreshToken = (http, { config }) => {
  if (isRefreshing === true) {
    return new Promise((resolve) => requests.push(() => resolve(http(config))));
  }
  isRefreshing = true;
  const { refreshToken } = getToken();
  return refreshTokenApi(refreshToken)
    .then((res) => handleResend(http, config, res))
    .finally(() => (isRefreshing = false));
};

/**
 * 令牌过期处理器策略
 *
 */
export default class HandleTokenExpire extends Handle {
  action(...args) {
    return handleRefreshToken(...args);
  }
}
